package main

import (
	"bytes"
	"io"
	"os"
	"os/signal"
	"sync"
	"syscall"
	"workflow/config"
	"workflow/controller"
	"workflow/job"
	"workflow/logger"
	"workflow/service"
)

func clean(done chan int, wg *sync.WaitGroup) {
	logger.Logger.Println("收到退出信号")
	defer logger.Close()

	done <- 1

	wg.Wait()

	logger.Logger.Println("安全退出")
}

func print_banner() {
	buffer := new(bytes.Buffer)
	buffer.Write(config.Config.Banner)

	for {
		line, err := buffer.ReadString('\n')
		logger.Logger.Print(line)
		if err == io.EOF {
			break
		}
	}
}

func main() {
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGINT)

	var wg sync.WaitGroup
	done := make(chan int)

	print_banner()

	go controller.Serve()

	wg.Add(1)
	go job.WorkflowDaemon(done, &wg)

	go job.TickerDaemon()

	service.ConfigTimer()

	select {
	case <-c:
		clean(done, &wg)
	}
}
